Two sum III - Data structure design¶
Time: O(N); Space: O(N); easy
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value.
Example 1:
Input: s = {TwoSum} [add(1); add(3); add(5)]
Output: [s.find(4)] True; [s.find(7)] False
[1]:
from collections import defaultdict
class TwoSum(object):
def __init__(self):
"""
initialize your data structure here
"""
self.lookup = defaultdict(int)
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
self.lookup[number] += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for key in self.lookup:
num = value - key
if num in self.lookup and (num != key or self.lookup[key] > 1):
return True
return False
[2]:
s = TwoSum()
s.add(1)
s.add(3)
s.add(5)
assert s.find(4) == True
assert s.find(7) == False
See also:¶
https://leetcode.com/problems/two-sum-iii-data-structure-design
https://www.lintcode.com/problem/two-sum-iii-data-structure-design/description
Related problems:¶
https://www.lintcode.com/problem/two-sum
https://www.lintcode.com/problem/two-sum-greater-than-target
https://www.lintcode.com/problem/two-sum-closest-to-target
https://www.lintcode.com/problem/two-sum-unique-pairs
https://www.lintcode.com/problem/two-sum-less-than-or-equal-to-target
https://www.lintcode.com/problem/two-sum-difference-equals-to-target
https://www.lintcode.com/problem/unique-word-abbreviation
https://www.lintcode.com/problem/two-sum-ii-input-array-is-sorted
https://www.lintcode.com/problem/k-difference